<template>
  <Dialog v-model="panelDialog" title="AI超级智能体" width="900px">
    <div class="panel-header">
      <div class="header-info">
        <el-icon class="info-icon"><InfoFilled /></el-icon>
        <el-text class="info-text">输入要创建的任务即可自动创建外呼任务</el-text>
      </div>
      <el-button class="clear-btn" link :icon="Delete" @click="clear">清空</el-button>
    </div>

    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message"
          :class="message.role"
        >
          <div class="message-wrapper" :class="message.role">
            <el-avatar :size="32" class="message-avatar" :src="AiImg" v-if="message.role == 'ai'" />
            <div class="message-content" :class="message.role">
              <div class="message-text">
                <!-- 如果是思考过程消息，特殊处理 -->
                <div v-if="message.isThinking" class="thinking-process">
                  <div class="thinking-header">
                    <el-icon class="thinking-icon"><Loading /></el-icon>
                    <span class="thinking-title">AI正在思考创建任务...</span>
                  </div>
                  <div class="thinking-steps">
                    <div
                      v-for="(step, stepIndex) in message.steps"
                      :key="stepIndex"
                      class="thinking-step"
                      :class="{
                        'step-executing': step.status === 'executing',
                        'step-completed': step.status === 'completed'
                      }"
                    >
                      <div class="step-number" v-html="step.displayNumber + '.'"></div>
                      <div class="step-content">
                        <div class="step-text" v-html="step.text"></div>
                        <div v-if="step.status === 'executing'" class="step-loading">
                          <div class="loading-dots"> <span></span><span></span><span></span> </div>
                        </div>
                        <div v-else-if="step.status === 'completed'" class="step-result">
                          <el-icon class="check-icon"><Check /></el-icon>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 普通消息 -->
                <span v-else v-html="message.content"></span>
              </div>
              <div class="message-time">{{ formatTime(new Date()) }}</div>
            </div>
            <el-avatar
              class="message-avatar"
              :size="32"
              :src="WoImg"
              v-if="message.role == 'user'"
            />
          </div>
        </div>

        <div class="empty-state" v-if="messages.length == 0">
          <el-icon class="empty-icon"><ChatDotRound /></el-icon>
          <p class="empty-text">开始与AI智能体对话吧</p>
          <p class="empty-subtext">描述您想要创建的外呼任务</p>
        </div>

        <div v-if="isLoading && !hasThinkingMessage" class="message ai">
          <div class="message-wrapper ai">
            <el-avatar :size="32" class="message-avatar" :src="AiImg" />
            <div class="message-content ai">
              <div class="loading-container">
                <span class="loading-text">AI正在思考</span>
                <div class="loading-dots"> <span></span><span></span><span></span> </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-container">
        <div class="input-wrapper">
          <el-input
            v-model="userInput"
            placeholder="请详细描述您要创建的外呼任务..."
            :disabled="isLoading"
            @keyup.enter="sendMessage"
            type="textarea"
            :rows="3"
            resize="none"
            class="chat-textarea"
          />
          <div class="input-actions">
            <div class="input-tip">
              <el-text size="small" type="info">Enter 发送</el-text>
            </div>
            <el-button
              type="primary"
              class="send-button"
              :disabled="isLoading || !userInput.trim()"
              @click="sendMessage"
              :loading="isLoading"
            >
              <el-icon><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </Dialog>
</template>

<script setup>
import { getTenantId, getAccessToken } from '@/utils/auth'
import { generateUUID } from '@/utils'
import { emitter } from '@/utils/eventBus.ts'
import {
  Delete,
  InfoFilled,
  ChatDotRound,
  Promotion,
  Loading,
  Check
} from '@element-plus/icons-vue'

import WoImg from '@/assets/img/wo.png'
import AiImg from '@/assets/img/ai.png'

const panelDialog = ref(false)
const userInput = ref('')
const messages = ref([])
const isLoading = ref(false)
const controller = ref(null)

const uuid = ref(null)
const baseUrl = ref('http://192.168.0.254:48081')

// 思考过程相关状态
const hasThinkingMessage = ref(false)
const currentThinkingMessage = ref(null)
// 存储所有步骤的映射，用于重新编号
const stepNumberMap = ref(new Map())

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理思考步骤 - 修改为支持type字段和重新编号
const processThinkingStep = (content, type) => {
  // 匹配步骤格式：数字.内容
  const stepMatch = content.match(/^(\d+)\.(.*)$/)
  if (!stepMatch) return null

  const originalStepNumber = parseInt(stepMatch[1])
  const stepText = stepMatch[2].trim()

  // 根据type判断状态：type 1为执行中，type 2为完成
  const status = type === 1 ? 'executing' : type === 2 ? 'completed' : 'normal'

  // 获取或分配新的显示编号
  let displayNumber
  if (!stepNumberMap.value.has(originalStepNumber)) {
    // 为新步骤分配连续的显示编号
    displayNumber = stepNumberMap.value.size + 1
    stepNumberMap.value.set(originalStepNumber, displayNumber)
  } else {
    displayNumber = stepNumberMap.value.get(originalStepNumber)
  }

  return {
    originalNumber: originalStepNumber,
    text: stepText,
    status: status,
    displayNumber: displayNumber
  }
}

// 更新思考消息 - 移除淡出逻辑，保留所有步骤
const updateThinkingMessage = (step) => {
  if (!currentThinkingMessage.value) {
    // 创建新的思考消息
    const thinkingMessage = {
      role: 'ai',
      content: '',
      isThinking: true,
      steps: []
    }
    messages.value.push(thinkingMessage)
    currentThinkingMessage.value = thinkingMessage
    hasThinkingMessage.value = true
  }

  const thinkingMsg = currentThinkingMessage.value
  const existingStepIndex = thinkingMsg.steps.findIndex(
    (s) => s.originalNumber === step.originalNumber
  )

  if (existingStepIndex !== -1) {
    // 更新现有步骤
    thinkingMsg.steps[existingStepIndex] = { ...thinkingMsg.steps[existingStepIndex], ...step }
  } else {
    // 添加新步骤，按显示编号排序
    thinkingMsg.steps.push(step)
    thinkingMsg.steps.sort((a, b) => a.displayNumber - b.displayNumber)
  }
}

// 完成思考过程，转换为普通消息
const completeThinkingProcess = () => {
  if (currentThinkingMessage.value) {
    // 将思考消息转换为普通消息，保留所有步骤内容
    const allSteps = currentThinkingMessage.value.steps
      .sort((a, b) => a.displayNumber - b.displayNumber)
      .map((step) => {
        const statusText = step.status === 'completed' ? step.text : step.text
        return `${step.displayNumber}. ${statusText}`
      })
      .join('<br>')

    currentThinkingMessage.value.isThinking = false
    currentThinkingMessage.value.content = allSteps || '任务处理完成'

    hasThinkingMessage.value = false
    currentThinkingMessage.value = null
  }
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  // 重置思考状态和步骤映射
  hasThinkingMessage.value = false
  currentThinkingMessage.value = null
  stepNumberMap.value.clear()

  // 添加用户消息到对话历史
  const userMessage = userInput.value.trim()

  messages.value.push({
    role: 'user',
    content: userMessage
  })
  await nextTick(() => {
    scrollToBottom()
  })
  // 清空输入框
  userInput.value = ''

  // 设置加载状态
  isLoading.value = true

  // 创建一个新的AbortController，用于取消请求
  controller.value = new AbortController()

  try {
    const url = baseUrl.value + '/admin-api/ai/manus/chat'

    // 使用fetch API代替axios
    const response = await fetch(
      url + `?message=${encodeURIComponent(userMessage)}&chatId=${uuid.value}`,
      {
        method: 'GET',
        headers: {
          Accept: '*',
          Authorization: 'Bearer ' + getAccessToken(),
          'tenant-id': getTenantId()
        },
        signal: controller.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()

      if (done) {
        break
      }

      // 解码数据并添加到缓冲区
      buffer += decoder.decode(value, { stream: true })

      // 处理缓冲区中的所有完整事件
      let eventEnd
      while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
        const eventStr = buffer.substring(0, eventEnd).trim()
        buffer = buffer.substring(eventEnd + 2)

        if (!eventStr.startsWith('data:')) continue

        const dataStr = eventStr.replace('data:', '').trim()

        try {
          const data = JSON.parse(dataStr)
          if (data.content === '[complete]') {
            emitter.emit('refreshAiTask')
            // 完成时，将思考消息转换为普通消息
            completeThinkingProcess()
            continue
          }

          if (data.content && data.content != '[complete]') {
            const content = data.content.trim()
            const type = data.type || 3 // 默认为type 3

            // 根据type处理不同类型的消息
            if (type === 1 || type === 2) {
              // type 1和2作为思考步骤处理
              const step = processThinkingStep(content, type)
              if (step) {
                updateThinkingMessage(step)
              }
            } else {
              // type 3及以后作为普通消息处理
              // 如果还有思考消息在进行，先完成它
              if (hasThinkingMessage.value) {
                completeThinkingProcess()
              }

              // 添加普通AI消息
              messages.value.push({
                role: 'ai',
                content: content
              })
            }

            // 滚动到底部
            nextTick(() => {
              scrollToBottom()
            })
          }
        } catch (e) {
          console.error('解析JSON失败:', e, '数据:', dataStr)
        }
      }
    }

    // 处理缓冲区中剩余的数据
    if (buffer.trim()) {
      const remainingData = buffer.trim()
      if (remainingData.startsWith('data:')) {
        const dataStr = remainingData.substring(5).trim()
        try {
          const data = JSON.parse(dataStr)
          if (data.content && data.content.trim()) {
            const content = data.content.trim()
            const type = data.type || 3

            if (type === 1 || type === 2) {
              const step = processThinkingStep(content, type)
              if (step) {
                updateThinkingMessage(step)
              }
            } else {
              if (hasThinkingMessage.value) {
                completeThinkingProcess()
              }
              messages.value.push({
                role: 'ai',
                content: content
              })
            }
          }
        } catch (e) {
          console.error('解析剩余数据失败:', e)
        }
      }
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled')
    } else {
      console.error('Error:', error)
      messages.value.push({
        role: 'system',
        content: `发生错误: ${error.message}`
      })
    }
  } finally {
    isLoading.value = false
    controller.value = null
    // 确保最后完成思考过程
    if (hasThinkingMessage.value) {
      completeThinkingProcess()
    }
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const messagesContainer = ref(null)
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const clear = () => {
  uuid.value = generateUUID()
  messages.value = []
  hasThinkingMessage.value = false
  currentThinkingMessage.value = null
  stepNumberMap.value.clear()
}

const open = () => {
  panelDialog.value = true
  uuid.value = generateUUID()
  baseUrl.value = 'https://mcp.jzsaas.com'
}

defineExpose({ open })
</script>

<style scoped>
/* 保持原有样式不变 */
/* 主容器样式 */
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e8f4ff;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-icon {
  color: #0052cc;
  font-size: 16px;
}

.info-text {
  color: #0052cc;
  font-weight: 500;
}

.clear-btn {
  color: #666;
  transition: all 0.2s ease;
}

.clear-btn:hover {
  color: #0052cc;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  max-width: 100%;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 82, 204, 0.08);
  border: 1px solid #e8f4ff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(180deg, #fafbff 0%, #f8faff 100%);
  scroll-behavior: smooth;
}

.message {
  margin-bottom: 20px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 85%;
}

.message-wrapper.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-wrapper.ai {
  margin-right: auto;
}

.message-avatar {
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.15);
}

.message-content {
  position: relative;
  border-radius: 16px;
  padding: 12px 16px;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.message-content.user {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message-content.ai {
  background: #ffffff;
  color: #333;
  border: 1px solid #e8f4ff;
  border-bottom-left-radius: 4px;
}

.message-text {
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
}

.message-content.ai .message-time {
  color: #999;
}

.message-content.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* 思考过程样式 */
.thinking-process {
  min-width: 300px;
}

.thinking-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8f4ff;
}

.thinking-icon {
  color: #0052cc;
  font-size: 16px;
  animation: spin 2s linear infinite;
}

.thinking-title {
  font-weight: 500;
  color: #0052cc;
}

.thinking-steps {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.thinking-step {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 8px;
  background: #f8faff;
  border: 1px solid #e8f4ff;
  transition: all 0.3s ease;
}

.thinking-step.step-executing {
  background: linear-gradient(135deg, #fff4e6 0%, #ffe7cc 100%);
  border-color: #ffd4a3;
}

.thinking-step.step-completed {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-color: #bae6fd;
}

.step-number {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  background: #0052cc;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
}

.step-executing .step-number {
  background: #ff8c00;
}

.step-completed .step-number {
  background: #10b981;
}

.step-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.step-text {
  flex: 1;
  font-size: 14px;
  line-height: 1.4;
}

.step-loading {
  margin-left: 12px;
}

.step-result {
  margin-left: 12px;
}

.check-icon {
  color: #10b981;
  font-size: 16px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #0052cc;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.empty-subtext {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  background: #0052cc;
  border-radius: 50%;
  animation: loading-bounce 1.4s infinite;
  opacity: 0.3;
}

.loading-dots span:nth-child(1) {
  animation-delay: 0s;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes loading-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.3;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 输入区域样式 */
.chat-input-container {
  background: #ffffff;
  border-top: 1px solid #e8f4ff;
  padding: 16px 20px;
}

.input-wrapper {
  position: relative;
}

.chat-textarea {
  margin-bottom: 12px;
}

.chat-textarea :deep(.el-textarea__inner) {
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  transition: all 0.2s ease;
}

.chat-textarea :deep(.el-textarea__inner):focus {
  border-color: #0052cc;
  box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.1);
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tip {
  color: #999;
}

.send-button {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.2);
}

.send-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.send-button:active {
  transform: translateY(0);
}

.send-button:disabled {
  background: #f5f7fa;
  color: #c0c4cc;
  transform: none;
  box-shadow: none;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f8faff;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(0, 82, 204, 0.2);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 82, 204, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 400px;
  }

  .message-wrapper {
    max-width: 95%;
  }

  .panel-header {
    padding: 12px 16px;
  }

  .chat-messages {
    padding: 16px;
  }

  .chat-input-container {
    padding: 12px 16px;
  }
}
</style>
